package com.platform.file.teamFc.controller;

import com.github.pagehelper.PageHelper;
import com.platform.common.core.domain.R;
import com.platform.common.core.exception.ServiceException;
import com.platform.common.core.utils.StringUtils;
import com.platform.common.core.utils.sql.SqlUtil;
import com.platform.common.core.web.controller.BaseController;
import com.platform.common.core.web.page.PageDomain;
import com.platform.common.core.web.page.TableDataInfo;
import com.platform.common.core.web.page.TableSupport;
import com.platform.file.constant.SysFileConstants;
import com.platform.file.domain.DicFileLog;
import com.platform.file.domain.dto.FileInfoDTO;
import com.platform.file.domain.request.ToStoreNetworkFilesRequest;
import com.platform.file.service.IDicFileLogService;
import com.platform.file.service.ISysFileService;
import com.platform.file.teamFc.domain.dto.FileDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

@Slf4j
@RequestMapping("/platFileFc")
@RestController
public class PlatFileFcController extends BaseController {

    @Resource
    private IDicFileLogService dicFileLogService;
    @Resource
    private ISysFileService sysFileService;
    @Value("${minio.bucketName}")
    public String bucketName;
    @Value("${share.file.downloadPrefix}")
    private String shareFileDownloadPrefix;
    @Value("${constant.config.endpoint}")
    private String endpoint;

    /**
     * 查询文件操作日志列表
     */
    @PostMapping("/list")
    public R<TableDataInfo> list(@RequestBody FileDTO fileDTO) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = fileDTO.getPageNum();
        Integer pageSize = fileDTO.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        String fileName = fileDTO.getFileName();
        DicFileLog dicFileLog = new DicFileLog();
        dicFileLog.setFileName(fileName);
        List<DicFileLog> list = dicFileLogService.selectDicFileLogList(dicFileLog);
        return R.ok(getDataTable(list), "文件列表查询成功！");
    }

    @PostMapping("/toStoreNetworkFiles")
    public R<FileInfoDTO> toStoreNetworkFiles(@RequestBody @Valid ToStoreNetworkFilesRequest request) {
        // 读取网络文件
        HttpURLConnection conn = null;
        InputStream fis = null;
        String pathParam;
        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bin = null;
        try {
            String url = request.getNetworkUrl();
            if (!url.startsWith("http")) {
                throw new ServiceException("网络地址不正确");
            }
            // 转换成代理地址
            String pattern = "^(https?://.*(\\.com|\\.cn|\\.gov|\\.org))";
            url = url.replaceAll(pattern, endpoint + "/nuonuoInvoice");
            URL path = new URL(url);
            conn = (HttpURLConnection) path.openConnection();
            conn.setConnectTimeout(10 * 1000);
            // 通过输入流获取数据
            fis = conn.getInputStream();
            byte[] getData = new byte[1024];
            int len;
            bos = new ByteArrayOutputStream();
            while ((len = fis.read(getData)) != -1) {
                bos.write(getData, 0, len);
            }
            getData = bos.toByteArray();
            BigDecimal size = new BigDecimal(getData.length);
            bin = new ByteArrayInputStream(getData);
            String contentType = conn.getContentType();
            String suffix = getFileSuffixByContentType(contentType);
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
            String xpath = getDatePath(LocalDate.now());
            String filePath = bucketName + "/" + SysFileConstants.NO_PERMISSION + "/" + request.getServiceName() + "/" + xpath + "/" + fileName;
            String savePath = filePath.replaceFirst(bucketName + "/", "");
            sysFileService.uploadFile(savePath, bin, contentType);
            String fileKey = UUID.randomUUID().toString().replaceAll("-", "");
            dicFileLogService.saveShareFile(request.getServiceName(), fileName, filePath, bucketName, contentType, size, fileKey);
            pathParam = fileKey;
        } catch (Exception ex) {
            log.error("下载文件异常:", ex);
            throw new ServiceException("下载异常，请稍后再试。");
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException ioe) {
                    log.error("下载文件->关闭流异常:", ioe);
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ioe) {
                    log.error("下载文件->关闭流异常:", ioe);
                }
            }
            if (bin != null) {
                try {
                    bin.close();
                } catch (IOException ioe) {
                    log.error("下载文件->关闭流异常:", ioe);
                }
            }
        }
        if (StringUtils.isBlank(pathParam)) {
            throw new ServiceException("文件转存储失败");
        }
        FileInfoDTO fileInfoDTO = new FileInfoDTO();
        fileInfoDTO.setFileUrl(shareFileDownloadPrefix);
        fileInfoDTO.setPathParam(pathParam);
        return R.ok(fileInfoDTO);
    }

    private String getDatePath(LocalDate date) {
        String dayOfMonth = String.format("%02d", date.getDayOfMonth());
        String month = String.format("%02d", date.getMonth().getValue());
        int year = date.getYear();
        return String.join("/", String.valueOf(year), month, dayOfMonth);
    }

    private String getFileSuffixByContentType(String contentType) {
        if (StringUtils.isBlank(contentType)) {
            throw new ServiceException("contentType为空");
        }
        switch (contentType) {
            case "image/jpeg":
                return "jpeg";
            case "image/jpg":
                return "jpg";
            case "image/png":
                return "png";
            case "text/plain":
                return "txt";
            case "docx":
            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                return "docx";
            case "application/pdf":
                return "pdf";
            case "application/vnd.ms-excel":
                return "xls";
            default:
                return "unknown";
        }
    }

    /**
     * 从输入流中获取数据
     *
     * @param fis : InputStream
     * @return byte[]
     * @author chenp
     * @date 2023/3/28 11:31
     */
    private byte[] readInputStream(InputStream fis) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        fis.close();
        return outStream.toByteArray();
    }

    public static void main1(String[] args) {
        HttpURLConnection conn = null;
        InputStream fis = null;
        try {
            String url = "https://inv.jss.com.cn/fp2/nE-7Uw9kSVWI7pTnhsXTqnq5LFdfSh7PEsJOBCp_jb3uwFop_1Wl09G6WxnQj9VDui04G70Nfdzk1lH-b3HNyQ.pdf";
            File file = new File(url);
            // 取得文件的后缀名。
            String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
            // 取的文件名
            String filename = url.substring(url.lastIndexOf("/") + 1);

            URL path = new URL(url);
            conn = (HttpURLConnection) path.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取数据
            fis = conn.getInputStream();
            String contentType = conn.getContentType();
            String filePath = SysFileConstants.NO_PERMISSION + "/" + "platform-file" + "/" + System.currentTimeMillis() + "_" + ".pdf";

        } catch (Exception ex) {
            log.error("下载文件异常:", ex);
            throw new ServiceException("下载异常，请稍后再试。");
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ioe) {
                    log.error("下载文件->关闭流异常:", ioe);
                }
            }
        }
    }
}
